<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		body, html {
			height: 100%;
			margin: 0;
		}
		.header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 10px 20px;
			/* 			background-color:gainsboro; */
		}
		.logo-title {
			display: flex;
			align-items: center;
			justify-content: center;
			flex: 1;
		}
		.logo {
			height: 50px;
		}

		.title {
			font-size: 24px;
			font-weight: bold;
		}

		.links {
			display: flex;
			align-items: center;
		}

		.links el-link {
			margin-left: 10px;
		}

		.user-info {
			display: flex;
			align-items: center;
		}

		.avatar {
			margin-right: 10px;
		}

		.username a {
			color: #333;
			text-decoration: none;
		}
		.container {
			display: flex;
			height: 100%;
		}
		.map-container {
			flex: 1; /* 地图容器占据剩余空间 */
		}
		#allmap {
			height: 400px;
			width: 100%;
			text-align: center;
		}
		.form-container {
			width: 40%;
			padding: 20px;
			padding-top:80px;
		}
		#result {
			position: fixed;
			top: 80px;
			left: 20px;
			width: 300px;
			height: 40px;
			line-height: 40px;
			text-align: center;
			background: #fff;
			box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
			border-radius: 7px;
			z-index: 99;
		}
		/* 蓝色点样式 */
		.blue-point {
			width: 10px;
			height: 10px;
			background-color: green;
			border-radius: 50%;
			margin-right: 10px;
			display: inline-block;
		}

		/* 红色点样式 */
		.red-point {
			width: 10px;
			height: 10px;
			background-color: red;
			border-radius: 50%;
			margin-right: 10px;
			display: inline-block;
		}
		.point-container {
			display: flex;
			align-items: center; /* 垂直居中对齐 */
		}
		.point-container .blue-point,
		.point-container .red-point {
			margin-right: 10px;
		}
		.input-field {
			max-width: 210px;
		}
		.order-dialog {
			margin: 0 auto; /* 水平居中对齐 */
		}

		.order-dialog .el-dialog__body {
			padding: 30px; /* 增加内边距 */
		}

		.order-info {
			margin-bottom: 20px;
		}

		.order-info p {
			margin: 5px 0;
		}

		.order-id-time {
			font-size: 16px;
			font-weight: bold;
		}

		.grid-container {
			display: grid;
			grid-template-columns: 1fr 1fr;
		}

		.grid-container div {
			margin-top: 10px;
			display: flex;
		}
		.grid-container strong {
			min-width: 80px;
			font-weight: bold;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.button-group {
			display: flex;
			justify-content: center;
			margin-top: 20px;
		}
		.divider {
			border-top: 1px solid #000;
			margin: 10px 0;
		}
		.arrival-time {
			position: absolute;
			bottom: 20px;
			left: 50%;
			transform: translateX(-50%);
			font-size: 16px;
			color: #ff4d4f;
		}
		.chat-container {
			display: flex;
			flex-direction: column;
			height: 400px;
		}
		.messages {
			flex: 1;
			overflow-y: auto;
			padding: 10px;
			border: 1px solid #ebeef5;
		}
		.message {
			display: flex;
			align-items: center;
			margin-bottom: 10px;
		}
		.message .avatar {
			width: 40px;
			height: 40px;
			margin-right: 10px;
			border-radius: 50%;
		}
		.message .content {
			max-width: 60%;
			padding: 10px;
			border-radius: 5px;
			background-color: #f2f2f2;
		}
		.message.sent .content {
			margin-left: auto;
			background-color: #cce5ff;
		}
		.message.sent .avatar {
			order: 2;
			margin-left: 10px;
		}
		.input-area {
			display: flex;
			align-items: center;
			padding-top: 10px;
		}
		.input-area el-input {
			flex: 1;
			margin-right: 10px;
		}
		.el-card {
			margin-bottom: 20px;
		}

		.divider-line {
			border: none;
			border-top: 1px solid #ccc;
			margin: 20px 0;
		}
		/* 移动端样式 */
		@media (max-width: 768px) {
			.header {
				flex-direction: column;
				align-items: flex-start;
			}

			.links {
				width: 100%;
				justify-content: space-around;
				position: fixed;
				bottom: 0;
				background-color: white;
				padding: 10px 0;
				box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
				z-index: 1000;
				margin-bottom: -10px;
				margin-left: -18px;
			}

			.links el-link {
				margin-left: 0;
			}

			.user-info {
				margin-top: 10px;
				width: 100%;
				justify-content: space-between;
			}
			.logo-title {
				display: flex;
				align-items: center;
				width: 100%;
				justify-content: center;
			}

			.logo {
				height: 40px;
			}

			.title {
				font-size: 20px;
			}
			.map-container {
				order: -1; /* 将地图容器移动到顶部 */
				width: 100%; /* 地图容器占满宽度 */
				margin-top: 20px; /* 在地图上方添加空间 */
				position: relative; /* 确保内部元素相对于地图容器定位 */
			}

			#allmap {
				width: 100%; /* 地图占满宽度 */
				height: 300px; /* 设置地图高度，适合移动设备 */
			}

			#result {
				position: absolute;
				top: 150px; /* 调整结果区域的位置 */
				left: 10px;
				width: auto;
				padding: 5px 10px; /* 调整内边距以改善移动设备显示效果 */
				background: rgba(255, 255, 255, 0.8); /* 背景透明度 */
				box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
			}
			.container {
				flex-direction: column; /* 垂直排列 */
			}

			.form-container {
				margin-top: 20px; /* 在表单容器上方添加空间 */
				width: 100%; /* 表单容器占满宽度 */
			}
		}
	</style>
	<script src="../js/vue.js"></script>
	<script src="../element-ui/lib/index.js"></script>
	<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
	<script src="../js/axios-0.18.0.js"></script>
	<!-- 引入百度地图 API -->
	<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
	<script src="https://api.map.baidu.com/api?v=1.0&amp;type=webgl&amp;ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
	<title>群星网约车</title>
	<link rel="icon" href="../image/carMR.png" type="image/png">
</head>
<body>
<div id="app">
	<div class="header">
		<div class="logo-title">
			<img class="logo" src="../image/carMR.png">
			<span class="title">群星网约车欢迎您</span>
		</div>
		<div class="links">
			<el-link href="userMain.html" target="_self" :underline="false">主页&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
			<el-link href="orderUserInfo.html" target="_self" :underline="false">我的订单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
			<el-link href="preferential.html" target="_blank" :underline="false">群星优惠&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
			<el-link href="taxiInfo.html" target="_blank" :underline="false">群星简介&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
			<el-link href="userInfo.html" target="_self" :underline="false">个人中心&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
		</div>
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		<div class="user-info">
			<div>
				<el-avatar :src="avatar"></el-avatar>
			</div>
			&nbsp;&nbsp;&nbsp;&nbsp;
			<span class="username"><a id="uname" href="javascript:void(0)">{{ displayUsername }}</a></span>
			&nbsp;&nbsp;&nbsp;&nbsp;
			<el-link target="_blank" :underline="false" @click="exitInfo">退出系统</el-link>
			&nbsp;&nbsp;&nbsp;&nbsp;
		</div>
	</div>
	<div class="container">
		<!-- 弹窗 -->
		<el-dialog :visible.sync="dialogVisible" title="订单详情" class="order-dialog">
			<div class="order-info">
				<p class="order-id-time"><strong>订单号：</strong>{{ orderId }}
					&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;				<strong>接单司机：</strong>{{ formattedUserName }}
				</p>
				<div class="divider"></div>
				<div class="grid-container">
					<div><strong>车辆类型：</strong>{{ orderDetails.vehicleType }}</div>
					<div><strong>车辆颜色：</strong>{{ orderDetails.color }}</div>
					<div><strong>车牌号码：</strong>{{ orderDetails.licensePlate }}</div>
					<div><strong>司机电话：</strong>{{ orderDetails.phoneNumber }}</div>
				</div>
			</div>
			<div class="button-group">
				<el-button @click="orderOk" type="primary" plain>收到</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogVisible1" title="司机提醒您是否已上车" class="order-dialog">
			<div class="button-group">
				<el-button @click="arriveGo" type="primary" plain>已上车</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogVisible2" title="发车刷新预计到达时间" class="order-dialog">
			<div class="button-group">
				<el-button @click="arriveGoTo" type="primary" plain>刷新</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogVisible3" title="确认到达" class="order-dialog">
			<div class="button-group">
				<el-button @click="noArrived" plain>未到达</el-button>
				<el-button @click="arrived" type="primary" plain>已到达</el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="dialogVisible4" title="优惠券信息" class="order-dialog">
			<div>
				<hr class="divider-line">
				<h3>优惠券生效中</h3>
				<el-row :gutter="20">
					<el-col :span="6" v-for="coupon in activeCoupons" :key="coupon.id">
						<el-card>
							<div>
								<strong>名称:</strong> {{ coupon.couponName }}
							</div>
							<div>
								<strong>数量:</strong> {{ coupon.couponNum }}
							</div>
							<div>
								<strong>开始时间:</strong> {{ coupon.validStart }}
							</div>
							<div>
								<strong>终止时间:</strong> {{ coupon.validUntil }}
							</div>
							<el-button type="primary" size="mini" @click="useCoupon(coupon.id,coupon.couponName)">使用</el-button>
						</el-card>
					</el-col>
				</el-row>
				<hr class="divider-line">
				<h3>优惠券已过期</h3>
				<el-row :gutter="20">
					<el-col :span="6" v-for="coupon in expiredCoupons" :key="coupon.id">
						<el-card>
							<div>
								<strong>名称:</strong> {{ coupon.couponName }}
							</div>
							<div>
								<strong>数量:</strong> {{ coupon.couponNum }}
							</div>
							<div>
								<strong>开始时间:</strong> {{ coupon.validStart }}
							</div>
							<div>
								<strong>终止时间:</strong> {{ coupon.validUntil }}
							</div>
						</el-card>
					</el-col>
				</el-row>
			</div>
			<hr class="divider-line">
			<div class="button-group">
				<el-button @click="noUseCoupon" type="primary" plain>不使用优惠券</el-button>
			</div>
		</el-dialog>

		<div class="map-container">
			<div id="allmap"></div>
		</div>
		<div class="form-container">
			<el-form ref="form" :model="form" label-width="80px">
				<el-form-item label="起点" style="margin-bottom: 0;">
					<div class="point-container">
						<div class="blue-point"></div> <!-- 绿色点表示起点 -->
						<el-input v-model="form.startPoint" class="input-field" readonly></el-input>
					</div>
				</el-form-item>
				<br>
				<el-form-item label="终点" style="margin-bottom: 0;">
					<div class="point-container">
						<div class="red-point"></div> <!-- 红色点表示终点 -->
						<el-input v-model="form.endPoint" class="input-field" readonly></el-input>
					</div>
				</el-form-item>
				<br>
				<el-form-item label="车型">&nbsp;&nbsp;&nbsp;&nbsp;
					<el-select v-model="form.select1" placeholder="请选择车辆类型" @change="calculateFare">
						<el-option label="经济型" value="经济型"></el-option>
						<el-option label="舒适型" value="舒适型"></el-option>
						<el-option label="豪华型" value="豪华型"></el-option>
						<el-option label="大型" value="大型"></el-option>
						<el-option label="绿色环保型" value="绿色环保型"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="颜色">&nbsp;&nbsp;&nbsp;&nbsp;
					<el-select v-model="form.select2" placeholder="请选择车辆颜色">
						<el-option label="白色" value="白色"></el-option>
						<el-option label="黑色" value="黑色"></el-option>
						<el-option label="银灰色" value="银灰色"></el-option>
						<el-option label="蓝色" value="蓝色"></el-option>
						<el-option label="红色" value="红色"></el-option>
						<el-option label="青绿色" value="青绿色"></el-option>
						<el-option label="金色" value="金色"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="总费用">&nbsp;&nbsp;&nbsp;&nbsp;
					<el-input v-model="totalFare" class="input-field" disabled></el-input>
				</el-form-item>
			</el-form>
			<el-button type="primary" @click="openChatDialog" style="margin-left:40px" v-show="showChatButton">与司机聊天</el-button>
		</div>
		<div v-if="arrivalTime" class="arrival-time">
			司机预计到达时间：{{ arrivalTime }}，请您耐心等待...
		</div>
		<el-button v-else type="primary" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);" @click="callDriver">打车</el-button>
		<el-dialog :visible.sync="chatDialogVisible" width="600px" :before-close="handleClose">
			<div class="chat-container">
				<div class="messages" ref="messages">
					<div v-for="msg in messages" :key="msg.id" :class="['message', { 'sent': msg.senderId === userId }]">
						<img :src="msg.senderAvatar" class="avatar">
						<div class="content">
							<strong>{{ msg.senderName }}</strong>
							<p v-html="msg.content"></p>
						</div>
					</div>
				</div>
				<div class="input-area">
					<el-input v-model="inputMessage" placeholder="请输入消息"></el-input>
					<el-button type="primary" @click="sendMessage">发送</el-button>
					<el-upload
							class="upload-demo"
							action="/user/users/common/upload"
							:on-success="handleUploadSuccess"
							:show-file-list="false">
						<el-button type="primary">上传图片</el-button>
					</el-upload>
					<emoji-picker @select="addEmoji"></emoji-picker>
				</div>
			</div>
		</el-dialog>
	</div>
</div>
<div id="result">路线行驶规划</div>
<script>
	// request拦截器，将用户token放入头中
	axios.interceptors.request.use(
			config => {
				let token = localStorage.getItem("token"); // 确保 token 正确存储在 localStorage 中
				if (token) {
					config.headers['token'] = token;
				}
				return config;
			},
			error => {
				console.log(error);
				return Promise.reject(error);
			}
	);
	new Vue({
		el: '#app',
		data: {
			coupons: [
				{
					id: 1,
					couponName: '优惠券1',
					couponNum: 10,
					validStart: '2023-01-01',
					validUntil: '2023-12-31'
				},
				{
					id: 2,
					couponName: '优惠券2',
					couponNum: 5,
					validStart: '2023-01-01',
					validUntil: '2023-06-30'
				}
			],
			form: {
				startPoint: '',
				endPoint: '',
				select1: '',
				select2: ''
			},
			time: '',
			distance: '',
			totalFare: null,
			actualAmount: null,
			userId: '',
			durationAndDistanceReady: false,
			orderId: '',
			userName: '',
			driverName:'',
			dialogVisible: false,
			dialogVisible1: false,
			dialogVisible2: false,
			dialogVisible3: false,
			dialogVisible4: false,
			websocket: null,
			confirmInstance: null,
			arrivalTime: null, // 初始化预计到达时间为空
			inputTime: '', // 用户输入的时间
			inputTime1: '',
			avatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
			orderDetails: {
				phoneNumber: '',
				licensePlate: '',
				vehicleType: '',
				color: ''
			},
			chatDialogVisible: false,
			inputMessage: '',
			messages: [],
			showChatButton:false,
			testDemo: 'false'
		},
		mounted() {
			this.form.startPoint=localStorage.getItem('searchInput1');
			this.form.endPoint=localStorage.getItem('searchInput');
			this.userId = localStorage.getItem('userId');
			this.userName = localStorage.getItem('userName');
			this.avatar = localStorage.getItem('pic');
			if (this.userName === null) {
				this.$message.error('非法进入,请先登录');
				setTimeout(() => {
					window.location.href = "../html/login.html";
				}, 3000); // 延迟2秒（2000毫秒）执行
			} else {
				this.initMap();
			}
			/*this.initMap();*/
		},
		methods: {
			noUseCoupon(){
				axios.get('/order/pay?total_amount='+this.totalFare).then(rs=>{
					window.open(rs.data);
				})
				const data={
					"orderId": this.orderId,
					"totalAmount": this.totalFare,
					"actualAmount": this.totalFare
				}
				axios.post('/order/orders/addAmount',data)
						.then(response => {
							if (response.data.code === 1) {
								console.log("更新成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						});
				axios.put('/order/orders/updateStatus1?orderId='+this.orderId)
						.then(response=>{
							if(response.data.code==1){
								console.log("订单完成");
							}
						});
			},
			useCoupon(couponId,couponName) {
				console.log('使用优惠券 ID:', couponId);
				const aChineseNumber = couponName.match(/[\u4e00-\u9fa5]/);
				const aDiscount = this.convertChineseNumberToArabic(aChineseNumber[0]);
				const cost=this.totalFare * aDiscount /10;
				this.actualAmount=cost;
				axios.get('/order/pay?total_amount='+cost).then(rs=>{
					window.open(rs.data);
				})
				axios.put('/user/users/updateCouponNum?id='+couponId)
						.then(response => {
							if (response.data.code === 1) {
								console.log("更新成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						});
				const data={
					"orderId": this.orderId,
					"totalAmount": this.totalFare,
					"actualAmount": this.actualAmount
				}
				axios.post('/order/orders/addAmount',data)
						.then(response => {
							if (response.data.code === 1) {
								console.log("更新成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						});
				axios.put('/order/orders/updateStatus1?orderId='+this.orderId)
						.then(response=>{
							if(response.data.code==1){
								console.log("订单完成");
							}
						});
			},
			calculateFare() {
				const fareRules = {
					经济型: { baseFare: 10, ratePerKm: 1.5 },
					舒适型: { baseFare: 15, ratePerKm: 2 },
					豪华型: { baseFare: 20, ratePerKm: 2.5 },
					大型: { baseFare: 25, ratePerKm: 3 },
					绿色环保型: { baseFare: 12, ratePerKm: 1.8 },
				};

				const selectedCarType = this.form.select1;
				const selectedDistance = parseFloat(this.distance.substring(0, 3)); // 将字符串距离转换为数字

				if (!isNaN(selectedDistance) && selectedCarType) {
					// 根据选择的车型获取价格规则
					const { baseFare, ratePerKm } = fareRules[selectedCarType];

					// 计算总费用
					const totalFare = baseFare + ratePerKm * selectedDistance;

					// 更新总费用显示
					this.totalFare = totalFare.toFixed(2); // 保留两位小数
				} else {
					this.totalFare = null;
				}
			},
			noArrived(){
				this.dialogVisible3=false;
				this.getCurrentLocation();
			},
			getCurrentLocation() {
				if (navigator.geolocation) {
					navigator.geolocation.getCurrentPosition(
							this.showPosition,
							this.showError
					);
				} else {
					alert('Geolocation is not supported by this browser.');
				}
			},
			showPosition(position) {
				const lat = position.coords.latitude;
				const lng = position.coords.longitude;
				this.getLocationName(lat, lng);
			},
			showError(error) {
				switch(error.code) {
					case error.PERMISSION_DENIED:
						alert("User denied the request for Geolocation.");
						break;
					case error.POSITION_UNAVAILABLE:
						alert("Location information is unavailable.");
						break;
					case error.TIMEOUT:
						alert("The request to get user location timed out.");
						break;
					case error.UNKNOWN_ERROR:
						alert("An unknown error occurred.");
						break;
				}
			},
			getLocationName(lat, lng) {
				const BMap = window.BMap;
				const point = new BMap.Point(lng, lat);
				const geoc = new BMap.Geocoder();

				geoc.getLocation(point, (result) => {
					if (result) {
						const locationName = result.address;
						this.sendLocationToBackend(locationName);
					} else {
						alert('Failed to get location name.');
					}
				});
			},
			sendLocationToBackend(locationName) {
				axios.post('/order/orders/addUserMsg', {
					location: locationName,
					orderId: this.orderId
				})
						.then(response => {
							console.log('Location sent successfully:', response);
							this.$message.success('发送成功...');
						})
						.catch(error => {
							console.error('Error sending location:', error);
						});
			},
			arrived(){
				this.dialogVisible3=false;
				this.dialogVisible4=true;
			},
			arriveGoTo(){
				if(this.testDemo=='true'){
					this.dialogVisible2=false;
					return;
				}
				this.dialogVisible2=false;
				this.testDemo='true';
				axios.get('/order/orders/getT1?orderId='+this.orderId)
						.then(response=>{
							if (response.data.code === 1) {
								this.inputTime1=response.data.data;
								const minutes = this.parseTimeInput(this.inputTime1);
								if (minutes !== null) {
									this.calculateArrivalTime(minutes); // 计算预计到达时间
								} else {
									// 处理无效输入
									alert('请输入有效的时间格式，如：5小时31分钟 或 26分钟');
								}
								console.log("成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						})
			},
			arriveGo(){
				this.dialogVisible1=false;
				axios.post('/order/orders/callDriver1?orderId='+this.orderId)
						.then(response=>{
							if(response.data.code==1){
								console.log("上车成功");
							}
						});
			},
			openChatDialog() {
				this.chatDialogVisible = true
				this.connectWebSocket()
			},
			connectWebSocket() {
				this.socket = new WebSocket(`ws://localhost:10010/order/ws/${this.orderId.toString()}/passenger`)
				this.socket.onopen = () => {
					console.log('WebSocket连接成功')
				}
				this.socket.onmessage = (event) => {
					const message = JSON.parse(event.data)
					this.messages.push({ id: new Date().getTime(), ...message })
					this.$nextTick(() => {
						this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight
					})
				}
				this.socket.onclose = () => {
					console.log('WebSocket连接关闭')
				}
				this.socket.onerror = (error) => {
					console.log('WebSocket错误', error)
				}
			},
			sendMessage() {
				if (this.inputMessage.trim() === '') return
				const message = {
					sessionId: this.userId.toString(),
					orderId: this.orderId.toString(),
					content: this.inputMessage,
					senderId: this.userId.toString(),
					senderName: this.userName,
					senderAvatar: this.avatar
				}
				this.socket.send(JSON.stringify(message))
				this.messages.push({ id: new Date().getTime(), ...message })
				this.inputMessage = ''
			},
			handleUploadSuccess(response, file) {
				const imageMessage = {
					id: new Date().getTime(),
					content: `<img src="${response.data}" />`,
					senderId: this.userId.toString(),
					senderName: this.userName,
					senderAvatar: this.avatar,
				}
				this.socket.send(JSON.stringify(imageMessage))
				this.messages.push(imageMessage)
			},
			addEmoji(emoji) {
				this.inputMessage += emoji.native
			},
			handleClose(done) {
				this.socket.close()
				done()
			},
			initWebSocket() {
				//let clientId = Math.random().toString(36).substr(2);
				console.log(this.userId + "098user");
				const socketUrl = 'ws://localhost:10010/order/ws/' + this.orderId.toString();
				if (typeof WebSocket === 'undefined') {
					this.$notify({
						title: '提示',
						message: '当前浏览器不支持 WebSocket，请使用最新版本的浏览器。',
						type: 'warning',
						duration: 0
					});
					return;
				}

				this.websocket = new WebSocket(socketUrl);

				this.websocket.onopen = () => {
					console.log('WebSocket 已连接');
				};

				this.websocket.onmessage = (msg) => {
					console.log('收到消息：', msg.data);
					const data = JSON.parse(msg.data);
					this.handleWebSocketMessage(data);
					console.log('你好000000000000000');
					this.$msgbox.close();
					this.confirmInstance.catch(() => {
						console.log('你好1000000000000000');
						this.$message.success('有司机接单啦...');
					});
				};

				this.websocket.onerror = (error) => {
					console.error('WebSocket 错误：', error);
					this.$notify({
						title: '错误',
						message: 'WebSocket 连接错误，请检查服务器状态。',
						type: 'error',
						duration: 0
					});
				};

				this.websocket.onclose = () => {
					console.log('WebSocket 已关闭');
				};
			},
			handleWebSocketMessage(data) {
				this.driverName=data.driverName;
				let title;
				if (data.type === 3) {
					title = '司机已到达';
				} else if (data.type === 2) {
					title = '接单提醒';
				} else if (data.type === 5) {
					title = '发车提醒';
				} else if(data.type === 6){
					title = '司机提醒: 已到达目的地';
				}
				const audio = new Audio('../video/passenger.mp3');
				audio.play();
				this.$notify({
					title: title,
					message: '订单编号：'+data.orderId+ ' 接单司机：' +data.driverName[0] + '师傅',
					type: 'info',
					duration: 0,
					/*						onClick:  data.type === 3 ? () => {
                                                console.log('通知1被点击');
                                                this.dialogVisible1 = true;
                                            } :() => {
                                                // 点击通知后的操作，例如跳转到订单详情页
                                                console.log('通知被点击');
                                                this.showOrderDetails(data);
                                            }*/
					onClick: () => {
						console.log('通知被点击');
						if (data.type === 2) {
							this.showOrderDetails(data);
						}else if(data.type === 3){
							this.dialogVisible1 = true;
						}else if(data.type === 5){
							console.log('发车提醒');
							this.dialogVisible2=true;
						}else if(data.type === 6){
							console.log('司机提醒: 已到达目的地');
							var userIdInt = parseInt(this.userId, 10);
							axios.get('/user/users/getCoupons?userId='+userIdInt)
									.then(response=>{
										if (response.data.code === 1) {
											this.coupons = response.data.data
													.filter(coupon => coupon.couponNum !== 0)
													.map(coupon => {
														return {
															...coupon,
															validStart: coupon.validStart.replace('T', ' '),
															validUntil: coupon.validUntil.replace('T', ' ')
														};
													})
													.sort((a, b) => {
														const aChineseNumber = a.couponName.match(/[\u4e00-\u9fa5]/);
														const bChineseNumber = b.couponName.match(/[\u4e00-\u9fa5]/);

														console.log('aChineseNumber:', aChineseNumber ? aChineseNumber[0] : 'not found', 'bChineseNumber:', bChineseNumber ? bChineseNumber[0] : 'not found');

														if (aChineseNumber && bChineseNumber) {
															const aDiscount = this.convertChineseNumberToArabic(aChineseNumber[0]);
															const bDiscount = this.convertChineseNumberToArabic(bChineseNumber[0]);

															console.log('aDiscount:', aDiscount, 'bDiscount:', bDiscount);

															return aDiscount - bDiscount;
														} else {
															// 若没有匹配到汉字数字则不进行排序
															return 0;
														}
													});
										} else {
											this.errorMessage = response.data.msg;
											this.$message.error(this.errorMessage);
										}
									})
							this.dialogVisible3=true;
						}
					}
				});
			},
			convertChineseNumberToArabic(chineseNumber) {
				const chineseToArabic = {
					'零': 0,
					'一': 1,
					'二': 2,
					'三': 3,
					'四': 4,
					'五': 5,
					'六': 6,
					'七': 7,
					'八': 8,
					'九': 9,
					'十': 10
				};
				let result = 0;
				for (let i = 0; i < chineseNumber.length; i++) {
					result += chineseToArabic[chineseNumber[i]];
				}
				console.log('convertChineseNumberToArabic - input:', chineseNumber, 'output:', result);
				return result;
			},
			showOrderDetails(data) {
				// 假设 data 包含完整的订单信息，如果不包含，需要额外的请求获取详细信息
				this.orderId=data.orderId;
				this.orderDetails = {
					phoneNumber: data.phoneNumber,
					licensePlate: data.licensePlate,
					vehicleType: data.vehicleType,
					color:data.color
				};
				this.dialogVisible = true;
				localStorage.setItem("orderId",this.orderId);
			},
			initMap() {
				var map = new BMapGL.Map('allmap');
				var point = new BMapGL.Point(116.51397, 39.73517);
				map.centerAndZoom(point, 11);
				map.enableScrollWheelZoom(true);
				map.addControl(new BMap.NavigationControl());

				// 从 localStorage 中取出四个值
				var peopleX = localStorage.getItem('peopleX');
				var peopleY = localStorage.getItem('peopleY');
				var bassX = localStorage.getItem('bassX');
				var bassY = localStorage.getItem('bassY');
				console.log(peopleX);
				console.log(peopleY);
				console.log(bassX);
				console.log(bassY);

				// 创建起点和终点的 BMapGL.Point 对象
				var start = new BMapGL.Point(parseFloat(peopleX), parseFloat(peopleY));
				var end = new BMapGL.Point(parseFloat(bassX), parseFloat(bassY));

				// 清除 localStorage 中的四个值
				localStorage.removeItem('peopleX');
				localStorage.removeItem('peopleY');
				localStorage.removeItem('bassX');
				localStorage.removeItem('bassY');

				// 创建驾车路线对象，并进行搜索
				var driving = new BMapGL.DrivingRoute(map, {
					renderOptions: {
						map: map,
						autoViewport: true,
						enableDragging: true,
					}
				});
				driving.search(start, end);
				var output = "驾车需要";
				var transit = new BMapGL.DrivingRoute(map, {
					renderOptions: { map: map },
					onSearchComplete: (results) => { // 使用箭头函数
						if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
							return;
						}
						var plan = results.getPlan(0);
						output += plan.getDuration(true); // 获取时间
						this.time = plan.getDuration(true);
						output += "总路程为：";
						output += plan.getDistance(true); // 获取距离
						this.distance = plan.getDistance(true);
						console.log(this.time);
						console.log(this.distance);
						// 设置标识为true，表示duration和distance已经获取到了
						this.durationAndDistanceReady = true;
					},
					onPolylinesSet: function() {
						setTimeout(function() { this.$message.success(output); }, 1000);
					}
				});
				transit.search(start, end);
			},
			orderOk(){
				if(this.arrivalTime!=null){
					this.dialogVisible = false;
					return;
				}
				this.dialogVisible = false;
				this.showChatButton=true;
				axios.get('/order/orders/getT?orderId='+this.orderId)
						.then(response=>{
							if (response.data.code === 1) {
								this.inputTime=response.data.data;
								const minutes = this.parseTimeInput(this.inputTime);
								if (minutes !== null) {
									this.calculateArrivalTime(minutes); // 计算预计到达时间
								} else {
									// 处理无效输入
									alert('请输入有效的时间格式，如：5小时31分钟 或 26分钟');
								}
								console.log("成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						})

			},
			parseTimeInput(input) {
				const dayHourMinuteRegex = /(\d+)\s*天\s*(\d+)\s*小时\s*(\d+)\s*分钟/;
				const dayHourRegex = /(\d+)\s*天\s*(\d+)\s*小时/;
				const hourMinuteRegex = /(\d+)\s*小时\s*(\d+)\s*分钟/;
				const minuteRegex = /(\d+)\s*分钟/;

				let minutes = 0;

				const dayHourMinuteMatch = input.match(dayHourMinuteRegex);
				if (dayHourMinuteMatch) {
					const days = parseInt(dayHourMinuteMatch[1], 10);
					const hours = parseInt(dayHourMinuteMatch[2], 10);
					const mins = parseInt(dayHourMinuteMatch[3], 10);
					minutes = days * 24 * 60 + hours * 60 + mins;
					return minutes;
				}

				const dayHourMatch = input.match(dayHourRegex);
				if (dayHourMatch) {
					const days = parseInt(dayHourMatch[1], 10);
					const hours = parseInt(dayHourMatch[2], 10);
					minutes = days * 24 * 60 + hours * 60;
					return minutes;
				}

				const hourMinuteMatch = input.match(hourMinuteRegex);
				if (hourMinuteMatch) {
					const hours = parseInt(hourMinuteMatch[1], 10);
					const mins = parseInt(hourMinuteMatch[2], 10);
					minutes = hours * 60 + mins;
					return minutes;
				}

				const minuteMatch = input.match(minuteRegex);
				if (minuteMatch) {
					minutes = parseInt(minuteMatch[1], 10);
					return minutes;
				}

				return null; // 解析失败返回 null
			},
			calculateArrivalTime(minutes) {
				const now = new Date();
				const arrivalTime = new Date(now.getTime() + minutes * 60000); // 将当前时间加上分钟数

				console.log(arrivalTime);

				// 获取当前日期和到达日期的天、月、年
				const nowDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const arrivalDate = new Date(arrivalTime.getFullYear(), arrivalTime.getMonth(), arrivalTime.getDate());

				// 计算天数差
				const days = (arrivalDate - nowDate) / (24 * 60 * 60 * 1000); // 天数差

				let arrivalHours = arrivalTime.getHours();
				let arrivalMinutes = arrivalTime.getMinutes();

				// 格式化时间为HH:mm
				const formattedHours = String(arrivalHours).padStart(2, '0');
				const formattedMinutes = String(arrivalMinutes).padStart(2, '0');

				if (days > 0) {
					this.arrivalTime = `${days}天后 ${formattedHours}:${formattedMinutes}`;
				} else {
					this.arrivalTime = `${formattedHours}:${formattedMinutes}`;
				}
			},
			callDriver() {
				if(!this.form.select1){
					this.$message.error('请选择车辆类型');
					return;
				}
				if(!this.form.select2){
					this.$message.error('请选择车辆颜色');
					return;
				}
				if (!this.durationAndDistanceReady) {
					this.$message.success('正在计算距离,请稍等...');
					return;
				}
				var userIdInt = parseInt(this.userId, 10);
				const data={
					userId: userIdInt,
					status: '1',
					departureLocation: this.form.startPoint,
					destinationLocation: this.form.endPoint,
					duration: this.time,
					distance: this.distance,
					type: this.form.select1,
					color: this.form.select2
				};
				console.log(data);
				axios.post('/order/orders/callDriver',data)
						.then(response => {
							if (response.data.code === 1) {
								this.orderId=response.data.data;
								this.initWebSocket();
								console.log(this.totalFare);
								const data1={
									orderId:this.orderId,
									totalAmount:this.totalFare
								}
								axios.post('/order/orders/addAmount1',data1)
										.then(response => {
											if (response.data.code === 1) {
												console.log("添加money成功");
											} else {
												this.errorMessage = response.data.msg;
												this.$message.error(this.errorMessage);
											}
										});
								console.log("成功");
							} else {
								this.errorMessage = response.data.msg;
								this.$message.error(this.errorMessage);
							}
						});
				this.confirmInstance = this.$confirm('正在呼叫司机...', '群星网约车为您服务', {
					confirmButtonText: '取消呼叫',
					cancelButtonText: '我知道了',
					closeOnClickModal: false,
					closeOnPressEscape: false,
					showClose: false,
					type: 'info'
				}).then(() => {
					// 取消呼叫的逻辑
					axios.post('/order/orders/cancelOrder?orderId='+this.orderId)
							.then(response => {
								if (response.data.code === 1) {
									console.log("取消成功");
									this.$message.success('取消呼叫成功');
								} else {
									this.errorMessage = response.data.msg;
									this.$message.error(this.errorMessage);
								}
							});
				}).catch(() => {
					// 用户点击了“我知道了”
					this.$message.success('后台呼叫ing...');
				});


				// 模拟司机接单的情况
				//  setTimeout(() => {
				// this.$confirm('司机已接单，司机信息：XXX', '司机接单', {
				//   confirmButtonText: '我知道了',
				//   showClose: false,
				//   type: 'success'
				// });
				//  }, 3000); // 这里模拟3秒后司机接单
			},
			exitInfo(){
				localStorage.removeItem('userId');
				localStorage.removeItem('userName');
				window.location.href = "../html/login.html"; // 页面跳转
			}
		},
		computed: {
			displayUsername() {
				// 如果 userName 不为空，显示 userName；否则显示 "未登录"
				return this.userName ? this.userName : "未登录";
			},
			// 计算属性，用于格式化用户名
			formattedUserName() {
				if (this.driverName && this.driverName.length > 0) {
					return this.driverName[0] + '师傅';
				} else {
					return '师傅';
				}
			},
			activeCoupons() {
				const now = new Date();
				return this.coupons.filter(coupon => new Date(coupon.validUntil) > now);
			},
			expiredCoupons() {
				const now = new Date();
				return this.coupons.filter(coupon => new Date(coupon.validUntil) <= now);
			}
		}
	});
</script>
<script>
</script>
</body>
</html>